//
//  RentalinformationVC.m
//  RENTVISITOR
//
//  Created by wonder on 2017/10/26.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "RentalinformationVC.h"
#import "RentVieitor.h"
#import "RentOptionView.h"
#import "AllHouseCell.h"
#import "HouseDetailViewController.h"
#import "FangModel.h"
#import "MJRefresh.h"
#import "QiuZuModel.h"
#import "RentInforCell.h"
@interface RentalinformationVC ()<LiaoRentDeleget,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    RentOptionView *optinView;
    NSInteger page;//页码
    UILabel   *navaLable;//
    UITextField *field;
    NSString *district;//区域
    NSString *rent_start;//最小租金
    NSString *rent_end;//最大租金'
    NSString *bedroom;//卧室数量
    NSString *characteristic;//特色
    NSString *title;//搜索关键字
    NSArray *moneyStart;
    NSArray *moneyEnd;

}
@property (nonatomic, strong)UITableView *tableView;

@end

@implementation RentalinformationVC
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, (64+50)*ScaleHeight, ScreenWidth, ScreenHeight-(114)*ScaleHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces  = YES;
        _tableView.tableFooterView = [[UIView alloc] init];
        [_tableView registerClass:[RentInforCell class] forCellReuseIdentifier:@"RentInforCell"];
    }
    return _tableView;
}
- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.data = [NSMutableArray array];
    self.view.backgroundColor = BackgroundColor;
    [self.view addSubview:self.tableView];
//    self.title = @"在租房源";
    page = 1;
    if (self.agent == nil) {
        self.agent = @"";
    }
//    moneyStart = @[@"",@"1",@"3000",@"4000",@"5000",@"6000",@"7000",@""];
//    moneyEnd = @[@"",@"3000",@"4000",@"5000",@"6000",@"7000",@"10000",@""];
    [self creatLeftView];
    [self creatView];
    [self reloadData];
    [self creatNavigationView];
}
- (void)creatNavigationView
{
     navaLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 200*ScaleWidth, 30)];
    navaLable.font = [UIFont systemFontOfSize:15];
    navaLable.textAlignment  = NSTextAlignmentCenter;
    navaLable.text = @"求租类型";
    self.navigationItem.titleView = navaLable;
}
- (void)creatLeftView
{
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 10,20 );
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏右侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 20, 20);
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"搜索icon"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;

}
- (void)creatView
{
    optinView = [[RentOptionView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 40) deleget:self];
    [optinView becomeFirstResponder];
    [self.view addSubview:optinView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh)];
    

}

- (void)reloadData
{
    [self.data removeAllObjects];
    if (self.data == nil) {
        self.data = [NSMutableArray array];
    }
    page = 1;
    if (bedroom == nil) {
        bedroom = @"";
    }
    if (district == nil) {
        district = @"";
    }
    if (characteristic == nil) {
        characteristic = @"";
    }
    if (rent_start == nil) {
        rent_start = @"";
    }
    if (rent_end == nil) {
        rent_end = @"";
    }
    if (title == nil) {
        title = @"";
    }
    NSString *url = [NSString stringWithFormat:@"%@qiuzu/list",Main_Url];
    NSDictionary *dic = @{
                          @"category":@"1001",
                          @"city":@"103",
                          @"bedroom":bedroom,
                          @"district":district,
                          @"characteristic":characteristic,
                          @"rent_start":rent_start,
                          @"rent_end":rent_end,
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          
                          @"title":title,
                          @"agent":self.agent,
                          @"region":@"",
                          @"square":@"",
                          @"rent":@"",
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSLog(@"str=%@",str);
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSLog(@"%@",md5String);
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    
    //    [param setValue:md5String forKey:@"sign"];
    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
//
//                FangModel *model = [[FangModel alloc] init];
//                [model setValuesForKeysWithDictionary:dic];
                QiuZuModel *model = [[QiuZuModel alloc]initWithDictionary:dic error:nil];
                [WeakSelf.data addObject:model];
            }
            
            [self.tableView   reloadData];
            [self.tableView.mj_header endRefreshing];
            if (WeakSelf.data.count == 10) {
                page ++;
            }
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        [self.tableView.mj_header endRefreshing];
    }];

}
- (void)headerRefresh
{
    bedroom = @"";
    district = @"";
    characteristic = @"";
    rent_start = @"";
    rent_end = @"";
    title = @"";
    
    [self.data removeAllObjects];
    if (self.data == nil) {
        self.data = [NSMutableArray array];
    }
    [self reloadData];
}
- (void)footRefresh
{
    page ++;
    __weak typeof(self)WeakSelf = self;
    NSString *url = [NSString stringWithFormat:@"%@qiuzu/list",Main_Url];
    NSDictionary *dic = @{
                          @"category":@"1001",
                          @"city":@"103",
                          @"bedroom":bedroom,
                          @"district":district,
                          @"characteristic":characteristic,
                          @"rent_start":rent_start,
                          @"rent_end":rent_end,
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          
                          @"title":title,
                          @"agent":self.agent,
                          @"region":@"",
                          @"square":@"",
                          @"rent":@"",
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSLog(@"str=%@",str);
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSLog(@"%@",md5String);
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        if ([response[@"code"] isEqualToString:@"10000"]) {
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
                QiuZuModel *model = [[QiuZuModel alloc]initWithDictionary:dic error:nil];
                [WeakSelf.data addObject:model];
            }
            
            [self.tableView   reloadData];
            [self.tableView.mj_header endRefreshing];
            if (WeakSelf.data.count == 10) {
                page ++;
            }
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        [self.tableView.mj_header endRefreshing];
    }];
}
#pragma mark 各种代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 228*ScaleHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RentInforCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RentInforCell" forIndexPath:indexPath];
    
    if (self.data.count > indexPath.row) {
        cell.model = self.data[indexPath.row];
    }
    return cell;
}
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    //    HouseDetailViewController *detailVc = [[HouseDetailViewController alloc] init];
//    //
//    //    if (self.data.count > indexPath.row) {
//    //
//    //        FangModel *model = self.data[indexPath.row];
//    //        detailVc.sn = model.sn;
//    //        [self.navigationController pushViewController:detailVc animated:YES];
//    //    }
//    ParkDetailVC *parkVc = [[ParkDetailVC alloc]init];
//    BuildingModel *model = self.data[indexPath.row];
//    parkVc.sn = model.sn;
//    //    [self.navigationController pushViewController:parkVc animated:YES];
//    parkVc.titleStr   = @"小区详情";
//    
//    [self presentViewController:parkVc animated:YES completion:nil];
//    NSLog(@"nihao");
//    
//    
//}

- (void)liaoOptionView:(RentOptionView *)option select:(NSString *)select index:(NSInteger)index {
    
    //    optinView.frame = CGRectMake(0, 0, KWidth, KHeight);
    if ( index == 100) {
        
        district = select;
    }else if(index == 101) {
        
        NSInteger selectIndex = [select integerValue];
        rent_start = moneyStart[selectIndex];
        rent_end = moneyEnd[selectIndex];
    }else if(index == 102) {
        
        bedroom = select;
    }else if(index == 103) {
        characteristic = select;
    }
}

- (void)liaoOptionView:(RentOptionView *)option changeFrame:(BOOL)isChange {
    
    if (isChange == YES) {
        optinView.frame = CGRectMake(0, 0, KWidth, 40);
    }else {
        optinView.frame = CGRectMake(0, 0, KWidth, KHeight);
    }
}


- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

//- (void)searchAction {
//    
//    title = field.text;
//    [self reloadData];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
